const ws = require('ws');

var websocketServer = new ws.Server({ port: 8099 });

//所有的客户端列表
var clientlist = {}
var id = 0;

websocketServer.on('connection', (client) => {
  client.id = id++;
  clientlist[id] = client;
  console.log('connection...')
  client.send('welcome to back')
  client.on('message', (msg) => {
    console.log(msg)
    boardcast(client.id + ":" + msg);
  })

  //client退出时的事件
  client.on('close', () => {
    boardcast(client.id + " 下线了");
    delete clientlist[client.id];
  })

})


//广博通知，所有客户端
function boardcast(message) {
  for (let o in clientlist) {
    clientlist[o].send(message)
  }
}